package cn.zhouyafeng.shares;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

public class ShareObj {


    public String code;
    public String name;
    public ShareObj(String code, String name) {
        this.name = name;
        this.code = code;
    }
    public ShareObj(String code, String name, Double oldPrice) {
        this.code = code;

        double price = oldPrice - oldPrice * 0.1;
        this.name = String.format(" - %s --%s-%s", price, name, oldPrice);
    }


    public static final String url = "http://hq.sinajs.cn/list=s_sh";


    public ShareResult getPrice() {
        try {
            return innerRun();
        } catch (Exception e) {
            String errormsg = e.toString();
            for (StackTraceElement element : e.getStackTrace()) {
                errormsg += "\n\t" + element;
            }
            System.out.println(errormsg);
            ShareResult res = new ShareResult();
            res.msg = errormsg;
            return res;
        }
    }

    private ShareResult innerRun() throws Exception{
        ShareResult res = new ShareResult();
        String msg = HttpClientService.sendGet(url + code);
        if (StringUtils.isBlank(msg)) {
            res.msg = "接口返回空";
            return res;
        }
        String[] arr = msg.split(",");
        // 分隔符不够用
        if (arr.length <= 2) {
            res.msg = msg;
            return res;
        }
        // 实际结果
        String priceStr = arr[1];
        Double price = NumberUtils.createDouble(priceStr);
        res.price = price;
        return res;

    }


    public String getName() {
        return name;
    }
}
